/**
 * Created by yuanyue on 2014-08-15.
 */

import com.eastcom.groovy.config.db.DstResource
import com.eastcom.groovy.config.itf.IBaseConfig
import com.eastcom.groovy.config.db.SrcResource
import com.eastcom.groovy.context.TaskContext
import com.eastcom.groovy.provider.SpringContextProvider
import com.eastcom.groovy.tools.db.DbEngine
import com.eastcom.groovy.tools.file.JaxbUtil
import com.eastcom.groovy.tools.TaskUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor

import javax.xml.bind.annotation.XmlAccessType
import javax.xml.bind.annotation.XmlAccessorType
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlTransient
import java.text.ParseException
import java.util.regex.Matcher
import java.util.regex.Pattern

DbEngine dbEngine;
/**
 * Created by yuanyue on 2014-08-13.
 */
@XmlRootElement(name = "fileContextList")
@XmlAccessorType(XmlAccessType.NONE)
class FileContextList {
    @XmlElement(name = "timeFormats")
    String timeFormatArr
    @XmlElement(name = "fileContext")
    List<FileContext> fileContextList
}

@XmlAccessorType(XmlAccessType.FIELD)
class FileContext {
    @XmlElement(name = "nameRegex")
    String nameRegex
    @XmlElement(name = "path")
    String path
    @XmlElement(name = "codeType")
    String codeType
    @XmlElement(name = "timeLimit")
    String timeLimit
    @XmlElement(name = "regexMap")
    List<RegexMap> regexMap
}
//@XmlAccessorType(XmlAccessType.FIELD)
//class RecordList{
//    @XmlElement(name = "record")
//    List<Record> recordList = new ArrayList<>()
//}
//@XmlAccessorType(XmlAccessType.FIELD)
//class Record{
//    @XmlElement(name = "name")
//    String name
//    @XmlElement(name = "dstDbname")
//    String dstDbname
//    @XmlElement(name = "dstTable")
//    String dstTable
//
//
//}
@XmlAccessorType(XmlAccessType.FIELD)
class RegexMap {
    @XmlElement(name = "dstDbfeild")
    String dstDbfeild
    @XmlElement(name = "fileTimeRegex")
    String fileTimeRegex
    @XmlElement(name = "fileTimeFormat")
    String fileTimeFormat
    @XmlElement(name = "regex")
    String regex
    @XmlElement(name = "matchId")
    String matchId
    @XmlElement(name = "minLinenum")
    String minLinenum

    @XmlTransient
    int t_minLineNum
    @XmlTransient
    List<Integer> t_matchId = new ArrayList<>()

    RegexMap() {
    }
}

//public void initConfig(String param){
////    println this.getBinding().getVariable("args")
////    String param = this.getBinding().getVariable("args")
//    String[] pArr = param.split(",")
//    FileContext testXml = JaxbUtil.converyFileToJavaBean(pArr[0],"UTF-8",FileContext.class)
//    System.out.println(testXml.recordList.getRecordList().get(0).regexMap.get(0).dstDbfeild)
//    println(pArr[1])
//    println(TaskContext.allTask.size())
//
////千万别忘了把这个类储存在TaskContext中
//    TaskContext.getTaskConfig().put(pArr[1],testXml)
//    println "任务"+pArr[1]+"配置初始化完成！"
//}

public Object getSrc(String param) {
//    println this.getBinding().getVariable("args")
//    String param = this.getBinding().getVariable("args")
    String[] pArr = param.split(",")
    FileContextList testXml = JaxbUtil.converyFileToJavaBean(TaskContext.taskRootPath.get(pArr[1]) + "//" + pArr[0], "UTF-8", FileContextList.class)
//    String[]timeFormat = testXml.timeFormatArr.split("\\s*,\\s*")
//    timeFormat.each {
//        TaskContext.timeFormatList.add(it)
//    }
    testXml.fileContextList.each {
        List<RegexMap> regexMapList = it.regexMap
        for(int i = 0 ; i < regexMapList.size(); i++){
            RegexMap regexMap= regexMapList.get(i)
            int minLine = Integer.valueOf(regexMap.minLinenum);
            regexMap.t_minLineNum = minLine
            String[] matchIds = regexMap.matchId.split("\\s*,\\s*")
            matchIds.each {
                regexMap.t_matchId.add(Integer.valueOf(it))
            }
        }
    }


//    System.out.println(testXml.recordList.getRecordList().get(0).regexMap.get(0).dstDbfeild)
//    testXml.each {
//        it.fileContextList.each {
//            it.regexMap.each {
//                it.regex
//            }
//        }
//    }
    println(pArr[1])
    println(TaskContext.allTask.size())
    println testXml.fileContextList.regexMap.get(0).dstDbfeild
//千万别忘了把这个类储存在TaskContext中
//    TaskContext.getTaskConfig().put(pArr[1],testXml)
    println "任务" + pArr[1] + "配置初始化完成！"
    return testXml
}
/**
 * 执行只要方法
 * @param jobId
 */

public boolean doJob(String jobId) {
//    List<FileContext> testXml
//    FileContextList fileContextList
//    String jobId = this.getBinding().getVariable("args")
    println("--------------fffffffffsddddddddddddddddddddddddddd")
    println(jobId)
//    TaskContext.taskMap.get(jobId).taskConfig.extern.config.configFile.

//    println fileContextList
//    testXml = fileContextList.fileContextList
//    println(testXml.size())
//    TaskContext.getTask(jobId).taskConfig.extern.config.
    println TaskContext.getTask(jobId).taskConfig
    TaskContext.getTask(jobId).taskConfig.dstResourceList.each {
//        DstResource dstResource = TaskContext.dstResourceMap.get(it)
        DstResource dstResource = it
//        List<Object> dstInsertValue = new ArrayList<>()
        it.srcResourceList.each {
//            it.
            SrcResource srcResource = it
            srcResource.insertParamList.clear()
            FileContextList fileContextList = it.detailContext
            int k = 1
            fileContextList.fileContextList.each {
                doMyJob(it, srcResource)
                println "文件内容解析完成第"+ k++ +"/"+fileContextList.fileContextList.size()+"部分"
            }
//            dstResource.insertDataList.addAll(srcResource.insertParamList)
//            dstInsertValue.addAll(srcResource.)
//            dstResource.insertDataList.
            List<Integer> typeList = new ArrayList<>()
            List<List<Object>> srcInsertParam = new ArrayList<>()
            srcResource.placeHolderIndexList.each {
                int type = dstResource.dstFieldTypeList.get(it)
                typeList.add(type)
            }
            srcResource.insertParamList.each {
                srcInsertParam.add(TaskUtil.fillInsertData(it,typeList,TaskContext.timeFormatList))
            }
            srcResource.insertParamList = srcInsertParam
        }
//        List<Integer> typeList = it.dstFieldTypeList

//        List<List<Object>> insertParamList = new ArrayList<>()
//        it.insertDataList.each {
//            insertParamList.add(TaskUtil.fillInsertData(it,typeList,TaskContext.timeFormatList))
//        }
//        it.insertDataList = insertParamList
//        insertParamList.each {
//            it.each {
//                println(it)
//            }
//        }
        ThreadPoolTaskExecutor threadPoolTaskExecutor =  SpringContextProvider.getBean("threadPool")
        threadPoolTaskExecutor.execute(
                new Runnable() {
                    @Override
                    void run() {
                        Thread.currentThread().setName(jobId)
                        dstResource.insertData()
                    }
                }
        )

        println "目的资源处理完成!"
//        List<List<Object>> insertParamObject = new ArrayList<>()
//        List<List<Object>> insertParamList = it.srcResourceList.get(0).insertParamList
//        for(int m = 1; m < it.srcResourceList.size(); m++){
////            List<Object> objects = insertParamList.get(m)
//            SrcResource srcResource = it.srcResourceList.get(m)
//            List<List<Object>> objects = srcResource.insertParamList
//            for(int n = 0; n < insertParamList.size(); n++){
//                insertParamList.get(n).addAll(objects.get(n))
//            }
////            objects.addAll()
//        }
//        insertParamList.each {
//            TaskUtil.fillInsertData(it,dstResource.insertData())
//        }
//        it.srcResourceList.each {
//            = it.insertParamList
//
//        }
    }
    println "任务" + jobId + "完成！"
    return true
}


private void doMyJob(FileContext file, SrcResource srcResource) {
    Log logger = LogFactory.getLog(this.class)
    List<List<Object>> paramList = new ArrayList<>();
    //目录
    String path = file.path
    String fileNameTimeValue = ""
    List<RegexMap> regexMapList = file.regexMap
    logger.debug("regexMapList.size="+regexMapList.size())
    File dir = new File(path);
    println path
    if (!dir.isDirectory()) {
        logger.debug("非法目录！");
        return;
    }
    logger.debug(dir)
    File[] f2 = dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir2, String name) {
            // TODO 自动生成的方法存根
            if (name.matches(file.nameRegex)) {
                logger.debug("接收文件：" + name);
                return true;
            }
            return false;
        }
    });
    logger.debug(f2)
    if (f2 == null) {
        logger.debug("没有文件!");
        return;
    }
    Calendar fileTime = Calendar.getInstance();
    Calendar fileLimitTime = Calendar.getInstance();
    long ft = Long.valueOf(file.timeLimit);
    fileLimitTime.setTimeInMillis(new Date().getTime() - ft);
    for (File file2 : f2) {
        long time = file2.lastModified();
        fileTime.setTimeInMillis(time);
        if (fileTime.before(fileLimitTime)) {
            continue;
        }
        fileNameTimeValue = "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file2), file.codeType));
        } catch (UnsupportedEncodingException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        String line = null;
        boolean isFileEnd = false;
        String fileName = file2.getName()
        Pattern pat = Pattern.compile(file.nameRegex);
        Matcher matcher = pat.matcher(fileName);
        if(matcher.find()){
            if (matcher.groupCount() >= 1) {
                for(int j = 1; j <= matcher.groupCount(); j++){
                    println matcher.group(j)
                    fileNameTimeValue += matcher.group(j)
                }
            }
        }
        println fileNameTimeValue.equals("")?"文件没有时间匹配！":"文件时间是："+fileNameTimeValue
        while (!isFileEnd) {
            List<Object> valueList = new ArrayList<>();
            if(!isFileEnd){
                srcResource.insertParamList.add(valueList)
            }
            if(!fileNameTimeValue.equals("")){
                valueList.add(fileNameTimeValue)
            }
            regexMapList.each {
                boolean isMatch = false
                String regex = it.getRegex();
                pat = Pattern.compile(regex.toString());
                StringBuffer fileContext = new StringBuffer()
                while(!isMatch){
                    for(int i = 0; i < it.t_minLineNum; i++){
                        line = reader.readLine()
                        if(line == null){
                            isFileEnd = true
                            break;
                        }
                        fileContext.append(line)
                    }
                    if(isFileEnd){
                        println("文件已经读完！")
                        break
                    }
                    println("line="+fileContext.toString())
                    matcher = pat.matcher(fileContext.toString());
                    if(matcher.find()){
                        println("匹配记录！")
                        it.t_matchId.each {
                            valueList.add(matcher.group(it))
                        }
                        isMatch = true
                    }else{
                        println("没有匹配！")
                    }
                }
            }
        }
        if(srcResource.insertParamList.size() > 0){
            srcResource.insertParamList.remove(srcResource.insertParamList.size()-1)
        }
        println("源数据记录数量="+srcResource.insertParamList.size())
    }
}